#!/usr/bin/perl
#code.pl
#creates code tables
#usage: perl code.pl -ulist UNITLIST -out OUTPUTFILE [-l CODELENGTH -h]
#UNITLIST: contains the list of all units 
#CODELENGTH: length of binary code in bit (should be about 120 if unit of length 6 are used)
#!Atention: all quantifiers [?*+] and special characters for regular expressions (such as "\" or "/") in transcription in the  UNITLIST have to be substituted (e.g. "?" with "!") (if using data_preapare.pl)

#Version: 1.1
#@autor: Igor Jauk

#Changelist:
#use of the config class
#help output
#default values for the codelength and the outputfile
#error handling if the unitlsit does not exist
#fixed output file

use FindBin qw($Bin);
use lib "$Bin/../libs";
use config;
my $USAGE = "perl code.pl -ulist UNITLIST [-l CODELENGTH -h]";

main();

sub main {
	my $cl = config->new(\@ARGV);
	if ($cl->optionflag("-h")) {
		print $USAGE."\n";
		exit;
	}
	die "error: no unit list specified.\nusage: $USAGE\n" if (!$cl->optionflag("-ulist"));

	@letters = ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
	my $unitlist = $cl->optionarg("-ulist");
	my $bitlength = $cl->optionarg("-l");
	$x = 0;
	$y = 0;
	$z = 0;
	if (!$cl->optionflag("-l")) {
		$bitlength = 120;
		print STDERR "warning: no code length specified. setting code legnth to $bitlength\n";
	}
	
	my $outputfile = "convert_tables.txt";
	print STDERR "creating output file $outputfile\n";

	open IN, "$unitlist" or die "could not open unit list $ARGV[0]\n";
	chomp(my @list = <IN>);
	close(IN);
	open OUT, ">$outputfile" or die "could not create output file $ARGV[1]\n";
	foreach (@list) {
		$coded = unpack("b$bitlength", $_);
		$ijcoded = $letters[$x].$letters[$y].$letters[$z];
		if ($z<25) {
			$z++;
		}
		elsif ($z==25 && $y<25) {
			$y++;
			$z = 0;
		}
		elsif ($z==25 && $y==25 && $x<25) {
			$x++;
			$y = 0;
			$z = 0;
		}
		else {
			die "error: too high unit amount\n";
		}
		print OUT "$_ $coded $ijcoded"."\n";
	}
	close(OUT);
	print "done.\n";
}
